<!--
 * @Author: your name
 * @Date: 2021-08-09 09:51:00
 * @LastEditTime: 2021-08-09 09:59:24
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \qrcode-scan\src\components\weChat.vue
-->
<template>
  <div class="fullScreen">
    <van-loading size="24px">扫码正在加载中...</van-loading>
  </div>
</template>

<script>
import { jsSignPackage } from "@/api/api";
import wx from "jweixin-module";
export default {
  data () {
    return {
      code: "",
      src: '',
    };
  },
  async mounted () {
    let src = this.GetQueryString('baseSrc')
    if (src) this.src = src
    await this.wxConfig()
    await this.scanQRCode()
  },
  methods: {
    GetQueryString (name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
      var r = window.location.search.substr(1).match(reg);
      if (r != null) return unescape(r[2]);
      return null;
    },
    wxConfig () {
      let url = encodeURIComponent(window.location.href.split('#')[0]);
      return new Promise((resolve, reject) => {
        jsSignPackage({url})
          .then(function (res) {
            wx.config({
								debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
								appId: res.data.appId, // 必填，公众号的唯一标识
								timestamp: res.data.timestamp, // 必填，生成签名的时间戳
								nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
								signature: res.data.signature, // 必填，签名，见附录1
								jsApiList: [
									'scanQRCode',
								], // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
							});
         
            resolve(res.data)
          })
          .catch(function (error) {
            reject(error)
            console.log(error);
          });
      })
    },
    scanQRCode() {
				let _this = this;
				wx.ready(function() {
					wx.scanQRCode({
						needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
						scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
						success: function(res) {
							let result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
							_this.callBackPage(result);
							
						},
						complete: function(res) {
							if(res.errMsg == 'scanQRCode:cancel')window.history.back();
						}
					});
				})
			},
      callBackPage(code){
         window.location.href = `${this.src}?code=${code}`;
      }
  }
}
</script>


<style  scoped>
.fullScreen {
  height: 100vh;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>>
